<?php
/**
 * Dod首页
 *
 * PHP version 5
 *
 * @package   Dod
 * @author    Garbin <huangjiabin@ec3s.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   SVN: $Id$
 */
namespace Project\Apps\Ecga\Jobs;

use \Project\Apps\Ecga\CliApplication;
use \Framework\Controller\CliController;
use \Framework\Services\Scheduler\ScheduleLogger;
use \Framework\System\Helper\MongoClient;
use \Framework\System\ConfigWrapper;

/**
 * Dod首页
 *
 * PHP version 5
 *
 * @package   Dod
 * @author    Garbin <huangjiabin@ec3s.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 **/
class ImportSkuSiteUrlsJob extends CliController
{

    /**
    * 加载参数配置
    *
    * @param stirng $action Action 名字
    *
    * @throws InvalidArgumentException
    *
    * @return array
    */
    public static function loadArgumentsConfig($action)
    {
        switch ($action) {
        case 'execute':
            return array();
        default:
            throw new InvalidArgumentException();
        }
    }

    /**
     * 默认Action
     *
     * @param CLIRequest $req CLI请求
     *
     * @return void
     */
    public static function execute($req)
    {
    	//$filename = $req->get('fileName', 'string');
    	//$uid = $req->get('uid', 'int');
    	//$filename = $req['fileName'];
    	//$uid = $req['uid'];
        $importFiles = model('ImportFiles')->getAll();
        $conf = ConfigWrapper::load()->services->gridfs;
        $mogo = MongoClient::getInstance();
        $gridFs = $mogo
            ->selectDB($conf->dbname)
            ->getGridFS();
        if ($importFiles) {
            foreach ($importFiles as $importFile) {
                $importFile->setAttribute('flags', 1);
                $importFile->save();
            }
            foreach ($importFiles as $importFile) {
                $id = new \MongoId($importFile->fileId);
                $file = $gridFs->findOne(array('_id' => $id));
                $fileContent = $file->getBytes();
                if (!is_dir(ROOT_PATH . '/logs/import/')) {
                    mkdir(ROOT_PATH . '/logs/import/');
                }
                $tmpFile = ROOT_PATH . '/logs/import/' . time() . '.csv';
                file_put_contents($tmpFile, $fileContent);
                self::_import($tmpFile, $importFile->userId);
                $gridFs->delete($id);
                $importFile->delete();
                @unlink($tmpFile);
            }
        }
    }
    
    /**
     * 执行导入
     * 
     * @param string $filename 文件名
     * @param int    $userId   用户Id
     * 
     * @return void
     */
    private static function _import($filename, $userId)
    {
        try {
            $getstream = fopen($filename, 'r');
        } catch (\Exception $e) {
            ScheduleLogger::FAILED('读取文件失败! 文件名: ' . $filename);
            return false;
        }
        $projects = model('Projects')->getProjects();
        $projectIds = array_keys($projects);
        $skuSiteUrlsModel = model('SkuSiteUrls');
        //跳过第一行文件说明 文件指针到下一行
        $row = fgetcsv($getstream);
        //跳过第一行表头 文件指针到下一行
        $row = fgetcsv($getstream);
        $privs = model('UserProjectPrivs')->getByUserIdToArray($userId);
        if ($userId != 1 && !$privs) {
            ScheduleLogger::FAILED('用户Id:' . $userId . ' 没有权限执行导入操作!');
            return;
    	}
    	$skus = array();
        while ($row = fgetcsv($getstream)) {
            $data = array(
                'sku' => $row[0],
                'siteId' => intval($row[2]),
                'skuUrl' => $row[3]
            );
            if (!isset($skus[$data['sku']]) || !$skus[$data['sku']]) {
                $skus[$data['sku']] = model('Skus')->getBySKU($data['sku']); 
            }
            if (!$skus[$data['sku']]) {
                ScheduleLogger::FAILED('SKU:' . $data['sku'] . ' 不存在');
                continue;
            }
            
            $sku = $skus[$data['sku']];
            if ($userId != 1 && (!isset($privs[$sku->projectId]) || !in_array('', $privs[$sku->projectId]['privs']))
            ) {
                ScheduleLogger::FAILED(
                    '用户Id: ' . $userId . ' 没有权限对SKU:' . $data['sku'] . ' 进行操作'
                );
                continue;
            }
            $item = $skuSiteUrlsModel->getBySKUAndSiteId($data['sku'], $data['siteId']);
            if (!$item) {
                //当数据库中没用该site地址记录并且此处导入的siteUrl不为空时, 创建
                if ($data['skuUrl'] != '') {
                    $skuSiteUrlsModel->create()->setAttributes($data)->save();
                }
            } else {
                //当数据库有该site地址记录而此次文件中设置了该数据为空, 删除
                if ($data['skuUrl'] == '') {
                    $item->delete();
                } elseif ($data['skuUrl'] != $item->skuUrl) {
                    //当数据库有该site地址记录而此次文件中设置的地址不相同, 更新
                    $item->setAttributes($data)->save();
                }
            }
        }
        echo '导入成功!' . $filename;
    }
}

